package com.teamone.etl.systemsettings.aspect;


import com.teamone.etl.systemsettings.controller.UserformController;
import com.teamone.etl.systemsettings.entity.LoginMessage;
import com.teamone.etl.systemsettings.entity.Userform;
import com.teamone.etl.systemsettings.service.LoginMessageService;
import com.teamone.etl.systemsettings.utils.AddressUtils;
import com.teamone.etl.systemsettings.utils.GetIpUtils;
import com.teamone.etl.systemsettings.utils.IpUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author huaiyu
 * @create 2021/1/22 14:38
 */
@Aspect
@Configuration
public class LoginMessageAspect {

    @Autowired(required = false)
    private HttpServletRequest request;

    @Resource
    private LoginMessageService loginMessageService;

    /**
     * AOP 切面
     *
     * @param joinPoint 直接切指定方法
     * @return 方法名
     * @throws Throwable
     */
    @After("execution(* com.teamone.etl.systemsettings.controller.UserformController.loginUser(..))")
    public Object adminControllerBeforeValidation(JoinPoint joinPoint) throws Throwable {

        Userform attribute = (Userform) request.getSession().getAttribute(UserformController.ADMIN_ID);

        LoginMessage loginMessage = new LoginMessage();
        loginMessage.setUserId(attribute.getId());
        loginMessage.setIpAddress(IpUtils.getIp(request));
        loginMessage.setLoginAddress(AddressUtils.getaddressbyip(IpUtils.getIp(request)));
        loginMessage.setLoginTime(new Date());
        loginMessage.setLoginStatus(0);
        //写数据库
        loginMessageService.loginRecord(loginMessage);

        Signature signature = joinPoint.getSignature();
        return signature;

    }
}
